package com.example.stray_animal_management_system.admin.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.stray_animal_management_system.admin.service.AnnouncementService;
import com.example.stray_animal_management_system.entity.Announcement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: panpan
 * @time: 2025/11/1
 */
@RestController
@RequestMapping("/api/announcements")
public class AnnouncementController {

    @Autowired
    private AnnouncementService announcementService;

    /**
     *
     * 展示公告
     */
    @GetMapping("/list")
    public List<Announcement> list() {
        return announcementService.list(Wrappers.<Announcement>lambdaQuery()
                .orderByDesc(Announcement::getPublishTime));
    }

    /**
     *
     * 添加公告
     */
    @PostMapping("/add")
    public String add(@RequestBody Announcement announcement) {
        announcementService.save(announcement);
        return "添加成功";
    }

    /**
     *
     * 更新公告
     */
    @PutMapping("/update/{id}")
    public String update(@PathVariable Integer id, @RequestBody Announcement announcement) {
        announcement.setId(id);
        announcementService.updateById(announcement);
        return "更新成功";
    }

    /**
     *
     * 删除公告
     */
    @DeleteMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        announcementService.removeById(id);
        return "删除成功";
    }

    /**
     *获取最新公告 展示在用户端
     *
     */
    @GetMapping("/latest")
    public Map<String, Object> getLatest() {
        Map<String, Object> res = new HashMap<>();
        Announcement latest = announcementService
                .lambdaQuery()
                .orderByDesc(Announcement::getPublishTime)
                .last("LIMIT 1")
                .one();
        if (latest != null) {
            res.put("code", 200);
            res.put("data", latest);
        } else {
            res.put("code", 404);
            res.put("msg", "暂无公告");
        }
        return res;
    }


}
